package com.da.web.select_bed.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.da.common.Result;
import com.da.web.school_student.entity.SchoolStudent;
import com.da.web.school_student.service.SchoolStudentService;
import com.da.web.select_bed.entity.ChangeStu;
import com.da.web.select_bed.entity.StuBed;
import com.da.web.select_bed.entity.StuBedVo;
import com.da.web.select_bed.service.StuBedService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author da
 * @time 2023/12/13 上午 9:19
 */
@RestController
@RequestMapping("/api/stuBed")
public class StuBedController {
    @Autowired
    private StuBedService stuBedService;
    @Autowired
    private SchoolStudentService schoolStudentService;

    //保存选择宿舍
    @PostMapping("/selectBedSave")
    public Result selectBedSave(@RequestBody StuBed stuBed) {
        //根据床位查询,是否被选过
        QueryWrapper<StuBed> query = new QueryWrapper<>();
        query.lambda().eq(StuBed::getBedId, stuBed.getBedId());
        StuBed bed = stuBedService.getOne(query);
        if (bed != null) {
            return Result.error("该床位已被占用");
        }
        //查询当前学生是否已经选择过床位
        QueryWrapper<StuBed> stuQuery = new QueryWrapper<>();
        stuQuery.lambda().eq(StuBed::getStuId, stuBed.getStuId());
        StuBed stu = stuBedService.getOne(stuQuery);
        if (stu != null) {
            return Result.error("你已经选择过床位,不要重复选择");
        }
        boolean save = stuBedService.save(stuBed);
        if (save) {
            return Result.success("选择成功");
        }
        return Result.error("选择失败");
    }


    //查询学生宿舍
    @GetMapping("/getStuBedList")
    public Result getStuBedList(Long stuId, String userType) {
        if (userType.equals("1")) {
            return Result.success("查询成功");
        }
        List<StuBedVo> bedList = stuBedService.getStuBedList(stuId);
        return Result.success("查询成功", bedList);
    }

    //查询学生列表
    @GetMapping("/getStuList")
    public Result getStuList(Long stuId) {
        //根据学生id查询到对应的班级
        SchoolStudent student = schoolStudentService.getById(stuId);
        //根据班级id查询学生列表
        List<ChangeStu> stuList = stuBedService.getStuList(student.getClassId());
        return Result.success("查询成功", stuList);
    }

    //删除学生入住信息
    @DeleteMapping("/{stuId}/{bedId}")
    public Result deleteBed(@PathVariable("stuId") Long stuId, @PathVariable("bedId") Long bedId) {
        QueryWrapper<StuBed> query = new QueryWrapper<>();
        query.lambda().eq(StuBed::getStuId, stuId)
                .eq(StuBed::getBedId, bedId);
        boolean remove = stuBedService.remove(query);
        if (remove) {
            return Result.success("删除成功");
        }
        return Result.error("删除失败");
    }


}
